﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace WebAPI.Utils
{
    public class ValidatetionHelper
    {

        // 通用模型数据验证测试
        static void ValidatetionTest()
        {
            var p = new Author
            {
                FirstName = "",
                LastName = "",
                Email = "www.baidu.com",
                PhoneNumber = "12345"
            };

            // 调用通用模型校验
            var result = ValidatetionHelper.IsValid(p);
            if (!result.IsVaild)
            {
                foreach (ErrorMember errorMember in result.ErrorMembers)
                {
                    // 控制台打印字段验证信息
                    Console.WriteLine($"{errorMember.ErrorMemberName}：{errorMember.ErrorMessage}");
                }
            }
            Console.WriteLine();

            // 调用通用模型校验，返回统一数据格式
            //var validInfo = ValidatetionHelper.GetValidInfo(p);
            //var options = new JsonSerializerOptions
            //{
            //    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, // 设置中文编码乱码
            //    WriteIndented = false
            //};
            //string jsonStr = JsonSerializer.Serialize(validInfo, options);
            //Console.WriteLine($"校验结果返回统一数据格式：{jsonStr}");
        }


        /// <summary>
        /// DTO 模型校验
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ValidResult IsValid(object value)
        {
            var result = new ValidResult();
            try
            {
                var validationContext = new ValidationContext(value);
                var results = new List<ValidationResult>();
                var isValid = Validator.TryValidateObject(value, validationContext, results, true);
                result.IsVaild = isValid;

                if (!isValid)
                {
                    foreach (var item in results)
                    {
                        result.ErrorMembers.Add(new ErrorMember
                        {
                            ErrorMessage = item.ErrorMessage,
                            ErrorMemberName = item.MemberNames.FirstOrDefault()
                        });
                    }
                }
            }
            catch (ValidationException ex)
            {
                result.IsVaild = false;
                result.ErrorMembers =
                [
                    new ErrorMember
                    {
                        ErrorMessage = ex.Message,
                        ErrorMemberName = "Internal error"
                    }
                ];
            }
            return result;
        }

        /// <summary>
        /// DTO 模型校验统一响应信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static ResponseInfo<ValidResult> GetValidInfo<T>(T model) where T : class
        {
            var result = new ResponseInfo<ValidResult>();
            var validResult = IsValid(model);
            if (!validResult.IsVaild)
            {
                result.Code = 420;
                result.Message = "DTO 模型参数值异常";
                result.Success = false;
                result.Data = validResult;
            }
            else
            {
                result.Code = 200;
                result.Success = true;
                result.Message = "DTO 模型参数值合法";
            }
            return result;
        }

    }

    internal class Author
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
    }
}